Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: Reactjs Interview Questions
Description: React is a JavaScript-based UI development library. Facebook and an open-source developer community run it. Although React is a library rather than a language, it is widely used in web development. The library first appeared in May 2013 and is now one of the most commonly used frontend libraries for web development.in this notes i have done 300+ interview questions and answers so that is best for interview from my side

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


React Interview Questions & Answers
Click :star:if you like the project
...
Follow me [@SudheerJonna](https://twitter
...

Note: This repository is specific to ReactJS
...


Downloading PDF/Epub formats
You can download the PDF and Epub version of this repository from the latest
run on the actions tab
...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

Questions
Core React
What is React?
What are the major features of React?
What is JSX?
What is the difference between Element and
Component?
How to create components in React?
When to use a Class Component over a Function
Component?
What are Pure Components?
What is state in React?
What are props in React?
What is the difference between state and props?
Why should we not update the state directly?
What is the purpose of callback function as an
argument of setState()?
What is the difference between HTML and React event
handling?
How to bind methods or event handlers in JSX
callbacks?
How to pass a parameter to an event handler or
callback?
What are synthetic events in React?
What are inline conditional expressions?
What is “key” prop and what is the benefit of using it
in arrays of elements?
What is the use of refs?
How to create refs?
What are forward refs?
1

No
...


Questions

60
61
62
63
64
65

How to use InnerHtml in React?
How to use styles in React?
How events are different in React?
What will happen if you use setState in constructor?
What is the impact of indexes as keys?
Is it good to use setState() in componentWillMount()
method?
What will happen if you use props in initial state?
How do you conditionally render components?
Why we need to be careful when spreading props on
DOM elements??
How you use decorators in React?
How do you memoize a component?
How you implement Server-Side Rendering or SSR?
How to enable production mode in React?
What is CRA and its benefits?
What is the lifecycle methods order in mounting?
What are the lifecycle methods going to be deprecated
in React v16?
What is the purpose of getDerivedStateFromProps()
lifecycle method?
What is the purpose of getSnapshotBeforeUpdate()
lifecycle method?
Do Hooks replace render props and higher order
components?
What is the recommended way for naming components?
What is the recommended ordering of methods in
component class?
What is a switching component?
Why we need to pass a function to setState()?
What is strict mode in React?
What are React Mixins?
Why is isMounted() an anti-pattern and what is the
proper solution?
What are the Pointer Events supported in React?
Why should component names start with capital letter?
Are custom DOM attributes supported in React v16?
What is the difference between constructor and
getInitialState?
Can you force a component to re-render without calling
setState?
What is the difference between super() and
super(props) in React using ES6 classes?
How to loop inside JSX?

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92

3

No
...

129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161

Questions
React Router
What is React Router?
How React Router is different from history library?
What are the components of React Router
v4?
What is the purpose of push and replace methods of
history?
How do you programmatically navigate using React
router v4?
How to get query parameters in React Router v4
Why you get “Router may have only one child element”
warning?
How to pass params to history
...


Questions

162
163
164

How to use connect from React Redux?
How to reset state in Redux?
Whats the purpose of at symbol in the redux connect
decorator?
What is the difference between React context and
React Redux?
Why are Redux state functions called reducers?
How to make AJAX request in Redux?
Should I keep all component’s state in Redux store?
What is the proper way to access Redux store?
What is the difference between component and
container in React Redux?
What is the purpose of the constants in Redux?
What are the different ways to write
mapDispatchToProps()?
What is the use of the ownProps parameter in
mapStateToProps() and mapDispatchToProps()?
How to structure Redux top level directories?
What is redux-saga?
What is the mental model of redux-saga?
What are the differences between call and put in
redux-saga
What is Redux Thunk?
What are the differences between redux-saga and
redux-thunk
What is Redux DevTools?
What are the features of Redux DevTools?
What are Redux selectors and Why to use them?
What is Redux Form?
What are the main features of Redux Form?
How to add multiple middlewares to Redux?
How to set initial state in Redux?
How Relay is different from Redux?
What is an action in Redux?
React Native
What is the difference between React Native and
React?
How to test React Native apps?
How to do logging in React Native?
How to debug your React Native?
React supported libraries and Integration
What is reselect and how it works?
What is Flow?
What is the difference between Flow and PropTypes?

165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
188
189
190
191
192
193
194

6

No
...
js?
What is the difference between React and Angular?
Why React tab is not showing up in DevTools?
What are styled components?
Give an example of Styled Components?
What is Relay?
How to use TypeScript in create-react-app application?
Miscellaneous
What are the main features of reselect library?
Give an example of reselect usage?
Does the statics object work with ES6 classes in React?
Can Redux only be used with React?
Do you need to have a particular build tool to use
Redux?
How Redux Form initialValues get updated from state?
How React PropTypes allow different type for one
prop?
Can I import an SVG file as react component?
Why are inline ref callbacks or functions not
recommended?
What is render hijacking in React?
What are HOC factory implementations?
How to pass numbers to React component?
Do I need to keep all my state into Redux? Should I
ever use react internal state?
What is the purpose of registerServiceWorker in React?
What is React memo function?
What is React lazy function?
How to prevent unnecessary updates using setState?
How do you render Array, Strings and Numbers in
React 16 Version?
How to use class field declarations syntax in React
classes?
What are hooks?
What rules need to be followed for hooks?
How to ensure hooks followed the rules in your project?
What are the differences between Flux and Redux?
What are the benefits of React Router V4?
Can you describe about componentDidCatch lifecycle
method signature?

206
207
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231

7

No
...


Questions

267

What are the conditions to safely use the index as a
key?
Is it keys should be globally unique?
What is the popular choice for form handling?
What are the advantages of formik over redux form
library?
Why do you not required to use inheritance?
Can I use web components in react application?
What is dynamic import?
What are loadable components?
What is suspense component?
What is route based code splitting?
Give an example on How to use context?
What is the purpose of default value in context?
How do you use contextType?
What is a consumer?
How do you solve performance corner cases while using
context?
What is the purpose of forward ref in HOCs?
Is it ref argument available for all functions or class
components?
Why do you need additional care for component
libraries while using forward refs?
How to create react class components without ES6?
Is it possible to use react without JSX?
What is diffing algorithm?
What are the rules covered by diffing algorithm?
When do you need to use refs?
Is it prop must be named as render for render props?
What are the problems of using render props with pure
components?
How do you create HOC using render props?
What is windowing technique?
How do you print falsy values in JSX?
What is the typical use case of portals?
How do you set default value for uncontrolled
component?
What is your favorite React stack?
What is the difference between Real DOM and Virtual
DOM?
How to add Bootstrap to a react application?
Can you list down top websites or applications using
react as front end framework?
Is it recommended to use CSS In JS technique in React?

268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301

9

No
...
9?
What is the purpose of eslint plugin for hooks?
What is the difference between Imperative and
Declarative in React?
What are the benefits of using typescript with reactjs?
How do you make sure that user remains authenticated
on page refresh while using Context API State
Management?
What are the benefits of new JSX transform?
How does new JSX transform different from old
transform?
How do you get redux scaffolding using
create-react-app?
What are React Server components?
What is prop drilling?
What is state mutation and how to prevent it?
What is the difference between useState and useRef
hook?

303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325

326
327
328
329
330
331
332

10

Core React
1
...
It is used
for handling view layer for web and mobile apps
...
React was first
deployed on Facebook’s News Feed in 2011 and on Instagram in 2012
...

What are the major features of React?
The major features of React are:
• It uses VirtualDOM instead of RealDOM considering that RealDOM manipulations are expensive
...

• Follows Unidirectional data flow or data binding
...

� Back to Top
3
...
Basically it just provides syntactic sugar for the
React
...

In the example below text inside

tag is returned as JavaScript function to the render function
...
Component {
render()
{
return(

{'Welcome to React
world!'}



)
} }
� Back to Top
4
...
Elements can
11

contain other Elements in their props
...

Once an element is created, it is never mutated
...
createElement(
'div',
{id: 'login-btn'},
'Login'
)
The above React
...
render():
Login

Whereas a component can be declared in several different ways
...

In either case, it takes props as an input, and returns a JSX tree as the
output:
const Button = ({ onLogin }) =>
Login

Then JSX gets transpiled to a React
...
createElement(
'div',
{ id: 'login-btn', onClick: onLogin },
'Login'
)
� Back to Top
5
...

1
...
Those are pure JavaScript functions that accept props object
as the first parameter and return React elements:

12

“jsx harmony function Greeting({ message }) {

{Hello, ${message}‘}

return

} “‘
2
...
The above function component can be written as:
jsx harmony
render() {
} }

class Greeting extends React
...
props
...

When to use a Class Component over a Function Component?
If the component needs state or lifecycle methods then use class component otherwise use function component
...
8 with
the addition of Hooks, you could use state , lifecycle methods and other
features that were only available in class component right in your function
component
...

What are Pure Components?
React
...
Component except
that it handles the shouldComponentUpdate() method for you
...
Component on the other hand won’t compare current props and state to next out of the box
...

� Back to Top
8
...
We should always try to make
our state as simple as possible and minimize the number of stateful components
...
Component { constructor(props)
{ super(props)
this
...
state
...
e
...

� Back to Top
9
...
They are single values or objects containing a set of values that are passed to components on creation using a
naming convention similar to HTML-tag attributes
...


14

The primary purpose of props in React is to provide following component
functionality:
1
...

2
...

3
...
props
...

For example, let us create an element with reactProp property:
jsx harmony



This reactProp (or whatever you came up with) name then becomes a
property attached to React’s native props object which originally already
exists on all components created using React library
...
reactProp
� Back to Top
10
...
While both of them
hold information that influences the output of render, they are different
in their functionality with respect to component
...

� Back to Top
11
...

//Wrong
this
...
message = 'Hello world'
Instead use setState() method
...
When state changes, the component responds by rerendering
...
setState({ message: 'Hello World' })
Note: You can directly assign to the state object either in constructor or
using latest javascript’s class field declaration syntax
...

What is the purpose of callback function as an argument of
setState()?
The callback function is invoked when setState finished and the component
gets rendered
...

Note: It is recommended to use lifecycle method rather than this callback
function
...
log('The name has updated and component re-ren
� Back to Top
13
...
In HTML, the event name usually represents in lowercase as a convention:
;
}
}
2
...

jsx harmony
is:', this)

handleClick = () => {
}

console
...
handleClick}>
me'}

{'Click

3
...

jsx harmony handleClick() {
console
...
handleClick()}>Click Me; }
Note: If the callback is passed as prop to child components, those components might do an extra re-rendering
...
bind() or public class fields syntax approach considering performance
...

How to pass a parameter to an event handler or callback?
You can use an arrow function to wrap around an event handler and pass
parameters:

17

jsx harmony }
� Back to Top
44
...
lazy function supports default exports only
...

It also ensures that tree shaking keeps working and don’t pull unused components
...
js
export const SomeComponent = /*
...
*/; and reexport MoreComponents
...
js javascript
// IntermediateComponent
...
/MoreComponents
...
/IntermediateComponent
...


32

Why React uses className over class attribute?
class is a keyword in JavaScript, and JSX is an extension of JavaScript
...

Pass a string as the className prop
...

What are fragments?
It’s a common pattern in React which is used for a component to return
multiple elements
...

jsx harmony render() {
return (
...
Fragment>
) }
There is also a shorter syntax, but it’s not supported in many tools:
jsx harmony render() {
return (




<>
) }



� Back to Top
47
...
Fragments are a bit faster and use less memory by not creating an
extra DOM node
...

2
...

3
...

� Back to Top
48
...


33

ReactDOM
...
The second argument is a DOM element
...

What are stateless components?
If the behaviour is independent of its state then it can be a stateless component
...
But unless you need to use a lifecycle hook in your components, you should go for function components
...

� Back to Top
50
...
These stateful components
are always class components and have a state that gets initialized in the
constructor
...
state = { count: 0 }
}
render() {
//
...
8 Update:
Hooks let you use state and other React features without writing classes
...

How to apply validation on props in React?
When the application is running in development mode, React will automatically check all props that we set on components to make sure they
have correct type
...
It’s disabled in production mode due to performance
impact
...

The set of predefined prop types:
1
...

3
...

5
...

7
...

9
...


PropTypes
...
string
PropTypes
...
object
PropTypes
...
node
PropTypes
...
bool
PropTypes
...
any

We can define propTypes for User component as below:
“‘jsx harmony import React from ‘react’ import PropTypes from ‘proptypes’
class User extends React
...
string
...
number
...
props
...
props
...
5 *PropTypes* were moved from `React
...
propTypes = {
name: PropTypes
...
isRequired,
age: PropTypes
...
isRequired
}
� Back to Top
52
...

2
...

4
...

JSX makes code easy to read and write
...

Easy to integrate with frameworks (Angular, Backbone) since it is
only a view library
...
Easy to write unit and integration tests with tools such as Jest
...

What are the limitations of React?
Apart from the advantages, there are few limitations of React too,
1
...

2
...

3
...

4
...


36

5
...

� Back to Top
54
...

A class component becomes an error boundary if it defines a new
lifecycle method called componentDidCatch(error, info) or static
getDerivedStateFromError():
“‘jsx harmony class ErrorBoundary extends React
...
state = { hasError: false } }
componentDidCatch(error, info) { // You can also log the error to an error
reporting service logErrorToMyService(error, info) }
static getDerivedStateFromError(error) { // Update state so the next render will show the fallback UI
...
state
...
’}
}
return this
...
children
}}
After that use it as a regular component:
```jsx harmony



� Back to Top
55
...

It has been renamed to
componentDidCatch in React v16
...

What are the recommended ways for static type checking?
Normally we use PropTypes library (React
...
5) for type checking in the React
applications
...

� Back to Top
57
...
Most of the components are not required to
use this module
...

2
...

4
...


render()
hydrate()
unmountComponentAtNode()
findDOMNode()
createPortal()

� Back to Top
58
...
If the React
element was previously rendered into container, it will perform an update
on it and only mutate the DOM as necessary to reflect the latest changes
...
render(element, container, [callback])
If the optional callback is provided, it will be executed after the component
is rendered or updated
...

What is ReactDOMServer?
The ReactDOMServer object enables you to render components to static
markup (typically used on node server)
...
The following methods can be used in both
the server and browser environments:
1
...
renderToStaticMarkup()
For example, you generally run a Node-based web server like Express,
Hapi, or Koa, and you call renderToString to render your root component
to a string, which you then send as response
...
/MyPage'
app
...
write('My Page')
res
...
write(renderToString())
res
...
end()
})
� Back to Top
60
...
Just like innerHTML, it is risky to use
this attribute considering cross-site scripting (XSS) attacks
...

In this example MyComponent uses dangerouslySetInnerHTML attribute
for setting HTML markup:
“‘jsx harmony function createMarkup() { return { __html: ‘First · Second’ } }
function MyComponent() { return
} “‘
� Back to Top
61
...
This is consistent with the DOM style
JavaScript property, is more efficient, and prevents XSS security holes
...
g
...
style
...

� Back to Top
62
...
React event handlers are named using camelCase, rather than lowercase
...
With JSX you pass a function as the event handler, rather than a
string
...

What will happen if you use setState() in constructor?
When you use setState(), then apart from assigning to the object state
React also re-renders the component and all its children
...
So
we need to use this
...

� Back to Top
64
...

In the below code snippet each element’s key will be based on ordering,
rather than tied to the data that is being represented
...

jsx harmony {todos
...
todo}

If you use element data for unique key, assuming todo
...

jsx harmony {todos
...
todo}

key={todo
...

Is it good to use setState() in componentWillMount() method?
Yes, it is safe to use setState() inside componentWillMount() method
...
componentWillMount() is
invoked immediately before mounting occurs
...
Avoid
introducing any side-effects or subscriptions in this method
...

jsx harmony componentDidMount() {
axios
...
then((result) => {
this
...
result
...

What will happen if you use props in initial state?
If the props on the component are changed without the component being
refreshed, the new prop value will never be displayed because the constructor function will never update the current state of the component
...

The below component won’t display the updated input value:
“‘jsx harmony class MyComponent extends React
...
state = {
records: [],
inputValue: this
...
inputValue
};
}
render() { return

41

{this
...
inputValue}
}}
Using props inside render method will update the value:
```jsx harmony
class MyComponent extends React
...
state = {
record: []
}
}
render() {
return
{this
...
inputValue}

}
}
� Back to Top
67
...
JSX does not render false or undefined, so you can use conditional
short-circuiting to render a given part of your component only if a certain
condition is true
...

jsx harmony const MyComponent = ({ name, address }) => (

{name}


{address
?

{address}


:

{'Address is not available'}


}
)
� Back to Top
68
...
Instead we can use prop destructuring
42

with
...

For example,
“‘jsx harmony const ComponentA = () =>
const ComponentB = ({ isDisplay, …domProps }) =>
{‘ComponentB’}
“‘
� Back to Top
69
...
Decorators are flexible and readable way of
modifying component functionality
...
Component
{ //…
...
Component { componentDidMount() { document
...
this
...

� Back to Top
70
...

For example moize library can memoize the component in another component
...
/components/Component’ // this module exports a non-memoized component

43

const MemoizedFoo = moize
...
6
...
memo`
...
memo(function MemoComponent(props) {
/* render using props */
});
OR
export default React
...

How you implement Server Side Rendering or SSR?
React is already equipped to handle rendering on Node servers
...

“‘jsx harmony import ReactDOMServer from ‘react-dom/server’ import
App from ‘
...
renderToString() “‘
This method will output the regular HTML as a string, which can be then
placed inside a page body as part of the server response
...

� Back to Top
72
...
Apart from this, if you minify the code, for example,
Uglify’s dead-code elimination to strip out development only code and
comments, it will drastically reduce the size of your bundle
...

44

What is CRA and its benefits?
The create-react-app CLI tool allows you to quickly create & run React
applications with no configuration step
...

2
...

4
...

Language extras beyond ES6 like the object spread operator
...

A fast interactive unit test runner with built-in support for coverage
reporting
...
A live development server that warns about common mistakes
...
A build script to bundle JS, CSS, and images for production, with
hashes and sourcemaps
...

What is the lifecycle methods order in mounting?
The lifecycle methods are called in the following order when an instance
of a component is being created and inserted into the DOM
...

2
...

4
...


45

What are the lifecycle methods going to be deprecated in React
v16?
The following lifecycle methods going to be unsafe coding practices and
will be more problematic with async rendering
...
componentWillMount()
2
...
componentWillUpdate()
Starting with React v16
...

� Back to Top
76
...
It can
return an object to update state, or null to indicate that the new props
do not require any state updates
...
Component {
static getDerivedStateFromProps(props, state) {
//
...

� Back to Top
77
...
The return value from this method will be passed
as the third parameter to componentDidUpdate()
...
Component {
getSnapshotBeforeUpdate(prevProps, prevState) {
//
...

� Back to Top
78
...

� Back to Top
79
...

Using displayName for naming component:
export default React
...

})
The recommended approach:
export default class TodoApp extends React
...

}
also
const TodoApp = () => {
//
...

What is the recommended ordering of methods in component
class?
Recommended ordering of methods from mounting to render stage:
1
...
constructor()
47

3
...

5
...

7
...

9
...

11
...
getter methods for render like getSelectReason() or getFooterContent()
13
...
render()
� Back to Top
81
...
We need to use object to map prop values to components
...
/HomePage’ import AboutPage
from ‘
...
/ServicesPage’ import ContactPage from ‘
...
page] || ContactPage
return }
// The keys of the PAGES object can be used in the prop types to catch
dev-time errors
...
propTypes = { page: PropTypes
...
keys(PAGES))
...

Why we need to pass a function to setState()?
The reason behind for this is that setState() is an asynchronous operation
...
That means you

48

should not rely on the current state when calling setState() since you
can’t be sure what that state will be
...
By doing this you
can avoid issues with the user getting the old state value on access due to
the asynchronous nature of setState()
...
After three consecutive increment
operations, the value is going to be incremented only by one
...
state
...
setState({ count: this
...
count + 1 })
this
...
state
...
setState({ count: this
...
count + 1 })
// this
...
count === 1, not 3
If we pass a function to setState(), the count gets incremented correctly
...
setState((prevState, props) => ({
count: prevState
...
increment
}))
// this
...
count === 3 as expected
(OR)
Why function is preferred over object for setState()?
React may batch multiple setState() calls into a single update for performance
...
props and this
...

This counter example will fail to update as expected:
// Wrong
this
...
state
...
props
...
That function will receive the previous state as the first argument,
and the props at the time the update is applied as the second argument
...
setState((prevState, props) => ({
counter: prevState
...
increment
}))
� Back to Top
83
...
StrictMode is a useful component for highlighting potential problems in an application
...
It activates additional checks and warnings for its descendants
...

“‘jsx harmony import React from ‘react’
function ExampleApplication() { return (

...
StrictMode>


) } “‘
In the example above, the strict mode checks apply to
and components only
...

What are React Mixins?
Mixins are a way to totally separate components to have a common functionality
...

One of the most commonly used mixins is PureRenderMixin
...
createClass({
mixins: [PureRenderMixin],
//
...


50

Why is isMounted() an anti-pattern and what is the proper solution?
The primary use case for isMounted() is to avoid calling setState() after
a component has been unmounted, because it will emit a warning
...
isMounted()) {
this
...
})
}
Checking isMounted() before calling setState() does eliminate the warning, but it also defeats the purpose of the warning
...

An optimal solution would be to find places where setState() might be
called after a component has unmounted, and fix them
...
Ideally, any callbacks should be canceled in componentWillUnmount(), prior to unmounting
...

What are the Pointer Events supported in React?
Pointer Events provide a unified way of handling all input events
...
We need to remember that
these events will only work in browsers that support the Pointer Events
specification
...

2
...

4
...

6
...

8
...

10
...

51

Why should component names start with capital letter?
If you are rendering your component using JSX, the name of that
component has to begin with a capital letter otherwise React will throw
an error as an unrecognized tag
...
jsx harmony
class SomeComponent extends Component { // Code goes here }
You can define component class which name starts with lowercase letter,
but when it’s imported it should have capital letter
...
/MyComponent'
What are the exceptions on React component naming? The component names should start with an uppercase letter but there are few exceptions to this convention
...
For example, the
below tag can be compiled to a valid component,
jsx harmony
render() {
return (
// `React
...
component)`

...

Are custom DOM attributes supported in React v16?
Yes
...
If you
wrote JSX with an attribute that React doesn’t recognize, React would
just skip it
...

� Back to Top
89
...
createClass()
...
Component {
constructor(props) {
super(props)
this
...
createClass():
const MyComponent = React
...
createClass() is deprecated and removed in React v16
...

� Back to Top
90
...
If your render() method depends on some other
data, you can tell React that the component needs re-rendering by calling
forceUpdate()
...
forceUpdate(callback)
It is recommended to avoid all uses of forceUpdate() and only read from
this
...
state in render()
...

53

What is the difference between super() and super(props) in React using ES6 classes?
When you want to access this
...

Using super(props):
class MyComponent extends React
...
log(this
...
}
}
}
Using super():
class MyComponent extends React
...
log(this
...
props
...

How to loop inside JSX?
You can simply use Array
...
map with ES6 arrow function syntax
...
map(item => key={item
...
name} />)}
But you can’t iterate using for loop:
jsx harmony
for (let i = 0; i < items
...
id} name={items[i]
...
This may change thanks to do expressions which are stage 1 proposal
...

How do you access props in attribute quotes?
React (or JSX) doesn’t support variable interpolation inside an attribute
value
...
props
...
So the below expression works:
jsx harmony ...
image}
/>
Using template strings will also work:
jsx harmony ...
image}`}
/>
� Back to Top
94
...
PropTypes
...
PropTypes
...

ReactComponent
...
PropTypes
...
PropTypes
...
PropTypes
...
isRequired,
fontSize: React
...
number
...
isRequired
}
� Back to Top
95
...

jsx harmony

Instead you need to move curly braces outside (don’t forget to include
spaces between class names):

55

jsx harmony
...
visible
? 'show' : 'hidden')}>
Template strings will also work:
jsx harmony
...
visible
? 'show' : 'hidden'}`}>
� Back to Top
96
...
createElement(), React
...
Children, and other helpers related to elements and component
classes
...
The react-dom package contains
ReactDOM
...
renderToString() and
ReactDOMServer
...

� Back to Top
97
...
But they are helpful as base parameters
...

Why React tab is not showing up in DevTools?
When the page loads, React DevTools sets a global named __REACT_DEVTOOLS_GLOBAL_HOOK__,
then React communicates with that hook during initialization
...

� Back to Top
202
...

It removes the mapping between styles and components, and lets you write
actual CSS augmented with JavaScript
...

Give an example of Styled Components?
Lets create and <Wrapper> components with specific styles for<br />each<br> ...<br> h1`<br />font-size: 1<br> ...<br> section`<br />padding: 4em;<br />background: papayawhip;<br />`<br />These two variables, Title and Wrapper, are now components that you<br />can render just like any other react component<br> ...<br> <br />What is Relay?<br />Relay is a JavaScript framework for providing a data layer and client-server<br />communication to web applications using the React view layer<br> ...<br> <br />How to use TypeScript in create-react-app application?<br />Starting from react-scripts@2<br> ...<br> 0 or higher, there is a built-in support for<br />typescript<br> ...<br> e, create-react-app now supports typescript natively<br> ...<br> <br />react-scripts-ts is a set of adjustments to take the standard<br />create-react-app project pipeline and bring TypeScript into the mix<br> ...<br> gitignore<br />�� images<br> ...<br> ts<br />�� node_modules/<br />�� public/<br />�� src/<br />� �� <br> ...<br> json<br />�� tsconfig<br> ...<br> prod<br> ...<br> test<br> ...<br> json<br /><br />Miscellaneous<br />� Back to Top<br />206<br> ...<br> Selectors can compute derived data, allowing Redux to store the minimal possible state<br> ...<br> Selectors are efficient<br> ...<br> <br />3<br> ...<br> They can be used as input to other selectors<br> ...<br> <br />Give an example of Reselect usage? Let’s take calculations and<br />different amounts of a shipment order with the simplified usage of Reselect:<br /><br />99<br /><br /> import { createSelector } from 'reselect'<br />const shopItemsSelector = state => state<br> ...<br> items<br />const taxPercentSelector = state => state<br> ...<br> taxPercent<br />const subtotalSelector = createSelector(<br />shopItemsSelector,<br />items => items<br> ...<br> value, 0)<br />)<br />const taxSelector = createSelector(<br />subtotalSelector,<br />taxPercentSelector,<br />(subtotal, taxPercent) => subtotal * (taxPercent / 100)<br />)<br />export const totalSelector = createSelector(<br />subtotalSelector,<br />taxSelector,<br />(subtotal, tax) => ({ total: subtotal + tax })<br />)<br />let exampleState = {<br />shop: {<br />taxPercent: 8,<br />items: [<br />{ name: 'apple', value: 1<br> ...<br> 95 },<br />]<br />}<br />}<br />console<br> ...<br> 15<br />console<br> ...<br> 172<br />console<br> ...<br> 322 }<br />� Back to Top<br />209<br> ...<br> createClass():<br />someComponent= React<br> ...<br> <br />}<br />}<br />})<br />But you can write statics inside ES6+ classes as below,<br />class Component extends React<br> ...<br> <br />}<br />static someMethod() {<br />// <br> ...<br> Component {<br /><br> ...<br> propTypes = {<br> ...<br> someMethod = function(){<br> ...<br> <br />Can Redux only be used with React?<br />Redux can be used as a data store for any UI layer<br> ...<br> Redux simply provides a<br />subscription mechanism which can be used by any other code<br> ...<br> <br />Do you need to have a particular build tool to use Redux?<br />Redux is originally written in ES6 and transpiled for production into ES5<br />with Webpack and Babel<br> ...<br> Redux also offers a UMD build that can be used<br />directly without any build process at all<br> ...<br> <br /><br />101<br /><br /> How Redux Form initialValues get updated from state?<br />You need to add enableReinitialize : true setting<br> ...<br> <br />� Back to Top<br />213<br> ...<br> <br />For example, the height property can be defined with either string or<br />number type as below:<br />Component<br> ...<br> oneOfType([<br />PropTypes<br> ...<br> number<br />])<br />}<br />� Back to Top<br />214<br> ...<br> <br />This feature is available with react-scripts@2<br> ...<br> 0 and higher<br> ...<br> /logo<br> ...<br> <br />� Back to Top<br />215<br> ...<br> <br />This is because a new instance of the function is created with each render,<br />so React needs to clear the old ref and set up the new one<br> ...<br> log("Input Value is: ", this<br> ...<br> value)<br />}<br /><br />render () {<br />return (<br /><form onSubmit={this<br> ...<br> input = input} /> // Access DOM input in handle submit<br /><button type='submit'>Submit</button><br /></form><br />)<br />}<br />}<br />But our expectation is for the ref callback to get called once, when the<br />component mounts<br> ...<br> log("Input Value is: ", this<br> ...<br> value)<br />}<br />setSearchInput = (input) => {<br />this<br> ...<br> handleSubmit}><br /><input<br />type='text'<br />ref={this<br> ...<br> 3,<br />� Back to Top<br />216<br> ...<br> It means that you decorate your<br />component by wrapping it into a Higher-Order component<br> ...<br> It does not actually enable hijacking, but by<br />using HOC you make your component behave differently<br> ...<br> <br />What are HOC factory implementations?<br />There are two main ways of implementing HOCs in React<br> ...<br> Props Proxy (PP) and<br />2<br> ...<br> <br />But they follow different approaches for manipulating the WrappedComponent<br> ...<br> We also pass through the props<br />that the HOC receives, hence the name Props Proxy<br> ...<br> Component {<br />render() {<br />return <WrappedComponent {<br> ...<br> props}/><br />}<br />}<br />}<br />Inheritance Inversion<br />In this approach, the returned HOC class (Enhancer) extends the<br />WrappedComponent<br> ...<br> In this way the relationship between them<br />seems inverse<br> ...<br> render()<br />}<br />}<br />}<br />� Back to Top<br />218<br> ...<br> render(<User age={30} department={"IT"} />, document<br> ...<br> <br />Do I need to keep all my state into Redux? Should I ever use<br />react internal state?<br />It is up to the developer’s decision, i<br> ...<br> , it is developer’s job to determine<br />what kinds of state make up your application, and where each piece of<br />state should live<br> ...<br> Others prefer to keep non-critical or UI state,<br />such as “is this dropdown currently open”, inside a component’s internal<br />state<br> ...<br> Do other parts of the application care about this data?<br />2<br> ...<br> Is the same data being used to drive multiple components?<br />4<br> ...<br> Do you want to cache the data (i<br> ...<br> <br />What is the purpose of registerServiceWorker in React?<br />React creates a service worker for you without any configuration by default<br> ...<br> <br />It’s all about adding offline capabilities to your site<br> ...<br> /App';<br />registerServiceWorker from '<br> ...<br> render(<App />, document<br> ...<br> <br />What is React memo function?<br />Class components can be restricted from re-rendering when their input<br />props are the same using PureComponent or shouldComponentUpdate<br> ...<br> memo<br> ...<br> memo(function MyComponent(props) {<br />/* only rerenders if props change */<br />});<br />� Back to Top<br />222<br> ...<br> lazy function lets you render a dynamic import as a regular component<br> ...<br> This must return<br />a Promise which resolves to a module with a default export containing a<br />React component<br> ...<br> lazy(() => import('<br> ...<br> lazy and Suspense is not yet available for server-side rendering<br> ...<br> <br />� Back to Top<br />223<br> ...<br> If the values are the same<br />then you need to return null to stop re-rendering otherwise return the<br />latest state value<br> ...<br> setState(state<br />if (state<br> ...<br> address;<br />=> {<br />=== latestAddress) {<br /><br />latestAddress };<br /><br />� Back to Top<br />224<br> ...<br> You are able to return multiple<br />sibling elements without a wrapping element by returning an array<br> ...<br> <br />const JSDevs = () => {<br />return (<br /><ul><br /><li>Brad</li><br /><li>Brodge</li><br /><ReactJSDevs/><br /><li>Brandon</li><br /></ul><br />);<br />}<br />Strings and Numbers: You can also return string and number type<br />from the render method<br> ...<br> <br />How to use class field declarations syntax in React classes?<br />React Class Components can be made much more concise using the class<br />field declarations<br> ...<br> <br />Let’s take a counter example to demonstrate class field declarations for<br />state without using constructor and methods without binding,<br />class Counter extends Component {<br />state = { value: 0 };<br />handleIncrement = () => {<br />this<br> ...<br> value + 1<br />}));<br />108<br /><br /> };<br />handleDecrement = () => {<br />this<br> ...<br> value - 1<br />}));<br />};<br />render() {<br />return (<br /><div><br />{this<br> ...<br> value}<br /><button onClick={this<br> ...<br> handleDecrement}>-</button><br /></div><br />)<br />}<br />}<br />� Back to Top<br />226<br> ...<br> 8) that lets you use state and other React<br />features without writing a class<br> ...<br> <br />What rules need to be followed for hooks?<br />You need to follow two rules in order to use hooks,<br />1<br> ...<br> i<br> ...<br> <br />This will ensure that Hooks are called in the same order each time<br />a component renders and it preserves the state of Hooks between<br />multiple useState and useEffect calls<br> ...<br> Call Hooks from React Functions only<br> ...<br> e, You shouldn’t call Hooks<br />from regular JavaScript functions<br> ...<br> <br />How to ensure hooks followed the rules in your project?<br />React team released an ESLint plugin called eslint-plugin-reacthooks that enforces these two rules<br> ...<br> <br />"react-hooks"<br />],<br />"rules": {<br />// <br> ...<br> <br />� Back to Top<br />229<br> ...<br> <br />What are the benefits of React Router V4?<br />Below are the main benefits of React Router V4 module,<br />1<br> ...<br> <br />A router can be visualized as a single component(<BrowserRouter>) which wraps specific child router components(<Route>)<br> ...<br> You don’t need to manually set history<br> ...<br> <br />3<br> ...<br> <br />Can you describe about componentDidCatch lifecycle method<br />signature?<br />The componentDidCatch lifecycle method is invoked after an error has<br />been thrown by a descendant component<br> ...<br> error: - The error object which was thrown<br />2<br> ...<br> <br />The method structure would be as follows<br />componentDidCatch(error, info)<br />� Back to Top<br />232<br> ...<br> Inside Event handlers<br />2<br> ...<br> During Server side rendering<br />4<br> ...<br> <br />111<br /><br /> Why do you not need error boundaries for event handlers?<br />Error boundaries do not catch errors inside event handlers<br> ...<br> Unlike the render method and lifecycle methods, the event handlers<br />don’t happen during rendering<br> ...<br> <br />If you need to catch an error inside an event handler, use the regular<br />JavaScript try / catch statement:<br />class MyComponent extends React<br> ...<br> state = { error: null };<br />this<br> ...<br> handleClick<br> ...<br> setState({ error });<br />}<br />}<br />render() {<br />if (this<br> ...<br> error) {<br />return <h1>Caught an error<br> ...<br> handleClick}>Click Me</button><br />}<br />}<br />Note that the above example is demonstrating regular JavaScript behavior<br />and doesn’t use error boundaries<br> ...<br> <br />What is the difference between try catch block and error boundaries?<br />Try catch block works with imperative code whereas error boundaries are<br />meant for declarative code to render on the screen<br> ...<br> <br />}<br />Whereas error boundaries wrap declarative code as below,<br /><ErrorBoundary><br /><MyComponent /><br /></ErrorBoundary><br />So if an error occurs in a componentDidUpdate method caused by a<br />setState somewhere deep in the tree, it will still correctly propagate to<br />the closest error boundary<br> ...<br> <br />What is the behavior of uncaught errors in react 16?<br />In React 16, errors that were not caught by any error boundary will result<br />in unmounting of the whole React component tree<br> ...<br> For example, it is worse for a payments app to<br />display a wrong amount than to render nothing<br> ...<br> <br />What is the proper placement for error boundaries?<br />The granularity of error boundaries usage is up to the developer based on<br />project needs<br> ...<br> You can wrap top-level route components to display a generic error<br />message for the entire application<br> ...<br> You can also wrap individual components in an error boundary to<br />protect them from crashing the rest of the application<br> ...<br> <br />What is the benefit of component stack trace from error boundary?<br />Apart from error messages and javascript stack, React16 will display the<br />component stack trace with file names and line numbers using error boundary concept<br> ...<br> <br />What is the required method to be defined for a class component?<br />The render() method is the only required method in a class component<br> ...<br> e, All methods other than render method are optional for a class component<br> ...<br> <br />What are the possible return types of render method?<br />Below are the list of following types used and return from render method,<br />1<br> ...<br> It includes html elements such as <div/> and user defined<br />elements<br> ...<br> Arrays and fragments: Return multiple elements to render as<br />Arrays and Fragments to wrap multiple elements<br />3<br> ...<br> <br />4<br> ...<br> Booleans or null: Doesn’t render anything but these types are used<br />to conditionally render content<br> ...<br> <br />What is the main purpose of constructor?<br />The constructor is mainly used for two purposes,<br />1<br> ...<br> state<br /><br />114<br /><br /> 2<br> ...<br> setState() here!<br />this<br> ...<br> handleClick = this<br> ...<br> bind(this);<br />}<br />� Back to Top<br />241<br> ...<br> i<br> ...<br> <br />� Back to Top<br />242<br> ...<br> This is used for undefined props, but not<br />for null props<br> ...<br> Component {<br />// <br> ...<br> defaultProps = {<br />color: 'red'<br />};<br />If props<br> ...<br> <br />i<br> ...<br> color will be set to red<br />}<br />Note: If you provide null value then it remains null value<br> ...<br> <br /><br />115<br /><br /> Why should not call setState in componentWillUnmount?<br />You should not call setState() in componentWillUnmount() because<br />once a component instance is unmounted, it will never be mounted again<br> ...<br> <br />What is the purpose of getDerivedStateFromError?<br />This lifecycle method is invoked after an error has been thrown by a descendant component<br> ...<br> <br />The signature of the lifecycle method is as follows,<br />static getDerivedStateFromError(error)<br />Let us take error boundary use case with the above lifecycle method for<br />demonstration purpose,<br />class ErrorBoundary extends React<br> ...<br> state = { hasError: false };<br />}<br />static getDerivedStateFromError(error) {<br />// Update state so the next render will show the fallback UI<br> ...<br> state<br> ...<br> </h1>;<br />}<br />return this<br> ...<br> children;<br />}<br />}<br />� Back to Top<br />245<br> ...<br> The below methods<br />are called in the following order when a component is being re-rendered<br> ...<br> <br />2<br> ...<br> <br />4<br> ...<br> <br /><br />static getDerivedStateFromProps()<br />shouldComponentUpdate()<br />render()<br />getSnapshotBeforeUpdate()<br />componentDidUpdate()<br /><br />� Back to Top<br />246<br> ...<br> <br />1<br> ...<br> componentDidCatch()<br />� Back to Top<br />247<br> ...<br> Usually, you don’t<br />need to set it explicitly because it’s inferred from the name of the function<br />or class that defines the component<br> ...<br> <br />For example, To ease debugging, choose a display name that communicates<br />that it’s the result of a withSubscription HOC<br> ...<br> Component {/* <br> ...<br> displayName = `WithSubscription(${getDisplayName(WrappedComponent)})<br />return WithSubscription;<br />}<br />function getDisplayName(WrappedComponent) {<br />return WrappedComponent<br> ...<br> name || 'Component';<br />}<br />� Back to Top<br />248<br> ...<br> If you use es5-shim and es5-sham polyfill then it even<br />support old browsers that doesn’t support ES5 methods<br> ...<br> <br />What is the purpose of unmountComponentAtNode method?<br />This method is available from react-dom package and it removes a<br />mounted React component from the DOM and clean up its event handlers and state<br> ...<br> Returns true if a component was unmounted<br />and false if there was no component to unmount<br> ...<br> unmountComponentAtNode(container)<br />� Back to Top<br />250<br> ...<br> The react project supports code splitting via dynamic<br />import() feature<br> ...<br> js and all<br />its unique dependencies as a separate chunk that only loads after the user<br />clicks the ‘Load’ button<br> ...<br> js<br />const moduleA = 'Hello';<br />export { moduleA };<br />App<br> ...<br> /moduleA')<br /><br> ...<br> catch(err => {<br />// Handle failure<br />});<br /><br />118<br /><br /> };<br />render() {<br />return (<br /><div><br /><button onClick={this<br> ...<br> <br />What is the benefit of strict mode?<br />The will be helpful in the below cases<br />1<br> ...<br> <br />3<br> ...<br> <br />5<br> ...<br> <br />Warning about legacy string ref API usage<br> ...<br> <br />Detecting legacy context API<br> ...<br> <br />What are Keyed Fragments?<br />The Fragments declared with the explicit <React<br> ...<br> The general use case is mapping a collection to an array of<br />fragments as below,<br />function Glossary(props) {<br />return (<br /><dl><br />{props<br> ...<br> map(item => (<br />// Without the `key`, React will fire a key warning<br /><React<br> ...<br> id}><br /><dt>{item<br> ...<br> description}</dd><br /></React<br> ...<br> In the<br />future, there might be a support for additional attributes, such as event<br />handlers<br> ...<br> <br />Does React support all HTML attributes?<br />As of React 16, both standard or custom DOM attributes are fully supported<br> ...<br> <br />Let us take few props with respect to standard HTML attributes,<br /><div tabIndex="-1" /><br />// Just like node<br> ...<br> className DOM API<br /><input readOnly={true} /> // Just like node<br> ...<br> It also support all SVG attributes<br> ...<br> <br />What are the limitations with HOCs?<br />Higher-order components come with a few caveats apart from its benefits<br> ...<br> Don’t use HOCs inside the render method: It is not recommended to apply a HOC to a component within the render method<br />of a component<br> ...<br> Instead, apply HOCs outside the component definition so that<br />the resulting component is created only once<br> ...<br> Static methods must be copied over: When you apply a HOC<br />to a component the new component does not have any of the static<br />methods of the original component<br />// Define a static method<br />WrappedComponent<br> ...<br> */ }<br />// Now apply a HOC<br />const EnhancedComponent = enhance(WrappedComponent);<br />// The enhanced component has no static method<br />typeof EnhancedComponent<br> ...<br> Component {/*<br> ...<br> staticMethod = WrappedComponent<br> ...<br> Refs aren’t passed through: For HOCs you need to pass through<br />all props to the wrapped component but this does not work for refs<br> ...<br> In this case<br />you need to use the React<br> ...<br> <br />How to debug forwardRefs in DevTools?<br />React<br> ...<br> <br />For example, If you don’t name the render function or not using displayName property then it will appear as ”ForwardRef” in the DevTools,<br />const WrappedComponent = React<br> ...<br> props} forwardedRef={ref} />;<br />});<br />But If you name the render function then it will appear as ”ForwardRef(myFunction)”<br />const WrappedComponent = React<br> ...<br> props} forwardedRef={ref} />;<br /><br />121<br /><br /> }<br />);<br />As an alternative, You can also set displayName property for forwardRef<br />function,<br />function logProps(Component) {<br />class LogProps extends React<br> ...<br> <br />}<br />function forwardRef(props, ref) {<br />return <LogProps {<br> ...<br> <br />// e<br> ...<br> "ForwardRef(logProps(MyComponent))"<br />const name = Component<br> ...<br> name;<br />forwardRef<br> ...<br> forwardRef(forwardRef);<br />}<br />� Back to Top<br />256<br> ...<br> This behavior is<br />available so that it matches the behavior of HTML<br> ...<br> <br />What is NextJS and major features of it?<br />Next<br> ...<br> It also provides styling<br />and routing solutions<br> ...<br> <br />2<br> ...<br> <br />4<br> ...<br> <br />6<br> ...<br> js HTTP server<br />Customizable with your own Babel and Webpack configurations<br /><br />� Back to Top<br />258<br> ...<br> It can be used in child component as below,<br /><button onClick={this<br> ...<br> <br />Is it good to use arrow functions in render methods?<br />Yes, You can use<br> ...<br> But you need to optimize the performance while using it<br> ...<br> log('Click happened');<br />}<br />render() {<br />return <button onClick={() => this<br> ...<br> <br />How to prevent a function from being called multiple times?<br />If you use an event handler such as onClick or onScroll and want to<br />prevent the callback from being fired too quickly, then you can limit the<br />rate at which callback is executed<br> ...<br> Throttling: Changes based on a time based frequency<br> ...<br> throttle lodash function<br />2<br> ...<br> For example, it can be used using _<br> ...<br> RequestAnimationFrame throttling: Changes based on requestAnimationFrame<br> ...<br> <br />How JSX prevents Injection Attacks?<br />React DOM escapes any values embedded in JSX before rendering them<br> ...<br> Everything is converted to a string before<br />being rendered<br> ...<br> potentiallyMaliciousInput;<br />const element = <h1>{name}</h1>;<br />This way you can prevent XSS(Cross-site-scripting) attacks in the application<br> ...<br> <br />How do you update rendered elements?<br />You can update UI(represented by rendered element) by passing the newly<br />created element to ReactDOM’s render method<br> ...<br> toLocaleTimeString()}<br> ...<br> render(element, document<br> ...<br> <br />How do you say that props are readonly?<br />When you declare a component as a function or a class, it must never<br />modify its own props<br> ...<br> Hence,<br />React has a single rule saying “All React components must act like pure<br />functions with respect to their props<br> ...<br> <br />How do you say that state updates are merged?<br />When you call setState() in the component, React merges the object you<br />provide into the current state<br> ...<br> state = {<br />posts: [],<br />comments: []<br />};<br />}<br />Now you can update them independently with separate setState() calls<br />as below,<br />componentDidMount() {<br />fetchPosts()<br> ...<br> setState({<br />posts: response<br> ...<br> then(response => {<br /><br />125<br /><br /> this<br> ...<br> comments<br />});<br />});<br />}<br />As mentioned in the above code snippets, this<br> ...<br> <br />� Back to Top<br />265<br> ...<br> This can be achieved through arrow functions or bind<br />method<br> ...<br> updateUser(userId, e)}>Update User details</button><br /><button onClick={this<br> ...<br> bind(this, userId)}>Update User details</button><br />In the both approaches, the synthetic argument e is passed as a second<br />argument<br> ...<br> <br />� Back to Top<br />266<br> ...<br> This way it can conditionally render component<br> ...<br> loggedIn) {<br />return null;<br />}<br />return (<br /><div className="greeting"><br />welcome, {props<br> ...<br> Component {<br />constructor(props) {<br />super(props);<br />this<br> ...<br> state<br> ...<br> state<br> ...<br> <br />� Back to Top<br />267<br> ...<br> <br />1<br> ...<br> The items in the list have no ids<br />3<br> ...<br> <br />� Back to Top<br />268<br> ...<br> i<br> ...<br> <br />For example, the below Book component uses two arrays with different<br />arrays,<br />function Book(props) {<br />const index = (<br /><ul><br />{props<br> ...<br> map((page) =><br /><li key={page<br> ...<br> title}<br /></li><br />)}<br /></ul><br />);<br />const content = props<br> ...<br> map((page) =><br /><div key={page<br> ...<br> title}</h3><br /><p>{page<br> ...<br> pageNumber}</p><br /></div><br />);<br />return (<br /><div><br />{index}<br /><hr /><br />{content}<br /></div><br />);<br />}<br />� Back to Top<br />269<br> ...<br> <br />In detail, You can categorize them as follows,<br />1<br> ...<br> Validation and error messages<br />3<br> ...<br> <br />� Back to Top<br />270<br> ...<br> The form state is inherently short-term and local, so tracking it in<br />Redux (or any kind of Flux library) is unnecessary<br> ...<br> Redux-Form calls your entire top-level Redux reducer multiple times<br />ON EVERY SINGLE KEYSTROKE<br> ...<br> <br />3<br> ...<br> 5 kB minified gzipped whereas Formik is 12<br> ...<br> <br />Why are you not required to use inheritance?<br />In React, it is recommended to use composition over inheritance to reuse<br />code between components<br> ...<br> Whereas, If you want to reuse non-UI functionality between components, it is suggested to extract it into a separate JavaScript<br />module<br> ...<br> <br />� Back to Top<br />272<br> ...<br> Even though<br />many developers won’t use this combination, it may require especially<br />if you are using third-party UI components that are written using Web<br />Components<br> ...<br> /App<br> ...<br> <br /><br />129<br /><br /> What is dynamic import?<br />You can achieve code-splitting in your app using dynamic import<br> ...<br> Normal Import<br />import { add } from '<br> ...<br> log(add(10, 20));<br />2<br> ...<br> /math")<br> ...<br> log(math<br> ...<br> <br />What are loadable components?<br />If you want to do code-splitting in a server rendered app, it is recommend<br />to use Loadable Components because React<br> ...<br> Loadable lets you render a dynamic<br />import as a regular component<br> ...<br> /OtherComponent'))<br />function MyComponent() {<br />return (<br /><div><br /><OtherComponent /><br /></div><br />)<br />}<br />Now OtherComponent will be loaded in a separated bundle<br />� Back to Top<br />275<br> ...<br> This can be<br />done using Suspense component<br> ...<br> lazy(() => import('<br> ...<br> </div>}><br /><OtherComponent /><br /></Suspense><br /></div><br />);<br />}<br />As mentioned in the above code, Suspense is wrapped above the lazy<br />component<br> ...<br> <br />What is route based code splitting?<br />One of the best place to do code splitting is with routes<br> ...<br> Due to this, the user experience<br />won’t be disturbed<br> ...<br> lazy,<br />import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';<br />import React, { Suspense, lazy } from 'react';<br />const Home = lazy(() => import('<br> ...<br> /routes/About'));<br />const App = () => (<br /><Router><br /><Suspense fallback={<div>Loading<br> ...<br> <br />� Back to Top<br />277<br> ...<br> <br />For example, in the code below lets manually thread through a “theme”<br />prop in order to style the Button component<br> ...<br> createContext('luna');<br />// Create App component where it uses provider to pass theme value in the tree<br />class App extends React<br> ...<br> Provider value="nova"><br /><Toolbar /><br /></ThemeContext<br> ...<br> Component {<br />static contextType = ThemeContext;<br />render() {<br />return <Button theme={this<br> ...<br> <br /><br />132<br /><br /> What is the purpose of default value in context?<br />The defaultValue argument is only used when a component does not have<br />a matching Provider above it in the tree<br> ...<br> <br />Below code snippet provides default theme value as Luna<br> ...<br> createContext(defaultValue);<br />� Back to Top<br />279<br> ...<br> The contextType<br />property can be used in two ways,<br />1<br> ...<br> createContext()<br> ...<br> context in any of the<br />lifecycle methods and render function<br> ...<br> Component {<br />componentDidMount() {<br />let value = this<br> ...<br> context;<br />/* <br> ...<br> context;<br />/* <br> ...<br> context;<br />/* render something based on the value of MyContext */<br />}<br />}<br />MyClass<br> ...<br> Static field You can use a static class field to initialize your contextType using public class field syntax<br> ...<br> Component {<br />static contextType = MyContext;<br />render() {<br />let value = this<br> ...<br> <br />What is a consumer?<br />A Consumer is a React component that subscribes to context changes<br> ...<br> The value argument passed to the<br />function will be equal to the value prop of the closest Provider for this<br />context above in the tree<br> ...<br> Consumer><br />{value => /* render something based on the context value */ }<br /></MyContext<br> ...<br> <br />How do you solve performance corner cases while using context?<br />The context uses reference identity to determine when to re-render, there<br />are some gotchas that could trigger unintentional renders in consumers<br />when a provider’s parent re-renders<br> ...<br> <br />class App extends React<br> ...<br> Component {<br />constructor(props) {<br />super(props);<br />this<br> ...<br> state<br> ...<br> <br />What is the purpose of forward ref in HOCs?<br />Refs will not get passed through because ref is not a prop<br> ...<br> If you add a ref to a HOC, the ref<br />will refer to the outermost container component, not the wrapped component<br> ...<br> For example, we<br />can explicitly forward refs to the inner FancyButton component using the<br />React<br> ...<br> <br />The below HOC logs all props,<br />function logProps(Component) {<br />class LogProps extends React<br> ...<br> log('old props:', prevProps);<br />console<br> ...<br> props);<br />}<br />render() {<br />const {forwardedRef, <br> ...<br> props;<br />// Assign the custom prop "forwardedRef" as a ref<br />return <Component ref={forwardedRef} {<br> ...<br> forwardRef((props, ref) => {<br />135<br /><br /> return <LogProps {<br> ...<br> Component {<br />focus() {<br />// <br> ...<br> <br />}<br />export default logProps(FancyButton);<br />Now let’s create a ref and pass it to FancyButton component<br> ...<br> <br />import FancyButton from '<br> ...<br> createRef();<br />ref<br> ...<br> focus();<br /><FancyButton<br />label="Click Me"<br />handleClick={handleClick}<br />ref={ref}<br />/>;<br />� Back to Top<br />283<br> ...<br> The second ref argument only exists<br />when you define a component with React<br> ...<br> <br />� Back to Top<br />284<br> ...<br> <br />This is because your library likely has a different behavior such as what<br /><br />136<br /><br /> refs get assigned to, and what types are exported<br> ...<br> <br />� Back to Top<br />285<br> ...<br> For default props, you need to define getDefaultProps()<br />as a function on the passed object<br> ...<br> <br />var Greeting = createReactClass({<br />getDefaultProps: function() {<br />return {<br />name: 'Jhohn'<br />};<br />},<br />getInitialState: function() {<br />return {message: this<br> ...<br> message};<br />},<br />handleClick: function() {<br />console<br> ...<br> state<br> ...<br> props<br> ...<br> i<br> ...<br> bind(this) with in constructor for<br />event handlers<br> ...<br> <br />Is it possible to use react without JSX?<br />Yes, JSX is not mandatory for using React<br> ...<br> Each JSX element is just syntactic sugar for calling<br />React<br> ...<br> children)<br> ...<br> Component {<br />render() {<br /><br />137<br /><br /> return <div>Hello {this<br> ...<br> message}</div>;<br />}<br />}<br />ReactDOM<br> ...<br> getElementById('root')<br />);<br />You can write the same code without JSX as below,<br />class Greeting extends React<br> ...<br> createElement('div', null, `Hello ${this<br> ...<br> message}`);<br />}<br />}<br />ReactDOM<br> ...<br> createElement(Greeting, {message: 'World'}, null),<br />document<br> ...<br> <br />What is diffing algorithm?<br />React needs to use algorithms to find out how to efficiently update the<br />UI to match the most recent tree<br> ...<br> <br />However, the algorithms have a complexity in the order of O(n3) where n<br />is the number of elements in the tree<br> ...<br> This is far too expensive<br> ...<br> Two elements of different types will produce different trees<br> ...<br> The developer can hint at which child elements may be stable across<br />different renders with a key prop<br> ...<br> <br />What are the rules covered by diffing algorithm?<br />When diffing two trees, React first compares the two root elements<br> ...<br> It covers<br /><br />138<br /><br /> the below rules during reconciliation algorithm,<br />1<br> ...<br> For example, elements to , or from<br />to of different types lead a full rebuild<br> ...<br> DOM Elements Of The Same Type: When comparing two React<br />DOM elements of the same type, React looks at the attributes of both,<br />keeps the same underlying DOM node, and only updates the changed<br />attributes<br> ...<br> Component Elements Of The Same Type: When a component<br />updates, the instance stays the same, so that state is maintained<br />across renders<br> ...<br> After that, the render() method is called and the diff algorithm recurses<br />on the previous result and the new result<br> ...<br> Recursing On Children: when recursing on the children of a DOM<br />node, React just iterates over both lists of children at the same time<br />and generates a mutation whenever there’s a difference<br> ...<br> <br /><ul><br /><li>first</li><br /><li>second</li><br /></ul><br /><ul><br /><li>first</li><br /><li>second</li><br /><li>third</li><br /></ul><br />5<br> ...<br> When children<br />have keys, React uses the key to match children in the original tree<br />with children in the subsequent tree<br> ...<br> <br />When do you need to use refs?<br />There are few use cases to go for refs,<br />1<br> ...<br> <br />2<br> ...<br> <br />3<br> ...<br> <br />� Back to Top<br />290<br> ...<br> i<br> ...<br> Lets take an example with the children prop for render props,<br /><Mouse children={mouse => (<br /><p>The mouse position is {mouse<br> ...<br> y}</p><br />)}/><br />Actually children prop doesn’t need to be named in the list of “attributes”<br />in JSX element<br> ...<br> x}, {mouse<br> ...<br> <br />Mouse<br> ...<br> func<br> ...<br> <br />What are the problems of using render props with pure components?<br />If you create a function inside a render method, it negates the purpose<br />of pure component<br> ...<br> You can solve this issue by defining the<br />render function as instance method<br> ...<br> <br />How do you create HOC using render props?<br />You can implement most higher-order components (HOC) using a regular<br />component with a render prop<br> ...<br> <br />function withMouse(Component) {<br />return class extends React<br> ...<br> this<br> ...<br> <br />� Back to Top<br />293<br> ...<br> If your<br />application renders long lists of data then this technique is recommended<br> ...<br> <br />� Back to Top<br />294<br> ...<br> If you still want to display them then you<br />need to convert it to string<br> ...<br> <br /></div><br />� Back to Top<br />295<br> ...<br> g<br> ...<br> <br />For example, dialogs, global message notifications, hovercards, and<br />tooltips<br> ...<br> <br />How do you set default value for uncontrolled component?<br />In React, the value attribute on form elements will override the value in<br />the DOM<br> ...<br> To<br />handle this case, you can specify a defaultValue attribute instead of<br />value<br> ...<br> handleSubmit}><br /><label><br />User Name:<br /><input<br />defaultValue="John"<br />type="text"<br />142<br /><br /> ref={this<br> ...<br> But you need to use<br />defaultChecked for checkbox and radio inputs<br> ...<br> <br />What is your favorite React stack?<br />Even though the tech stack varies from developer to developer, the most<br />popular stack is used in react boilerplate project code<br> ...<br> You can clone the project<br />https://github<br> ...<br> <br />� Back to Top<br />298<br> ...<br> <br />You can update HTML directly<br> ...<br> <br />How to add Bootstrap to a react application?<br />Bootstrap can be added to your React app in a three possible ways,<br /><br />143<br /><br /> 1<br> ...<br> <br />Add both bootstrap CSS and JS resources in a head tag<br> ...<br> Bootstrap as Dependency: If you are using a build tool or a module<br />bundler such as Webpack, then this is the preferred option for adding<br />Bootstrap to your React application<br />npm install bootstrap<br />3<br> ...<br> Below packages are<br />popular in this category,<br />1<br> ...<br> reactstrap<br />� Back to Top<br />300<br> ...<br> <br />2<br> ...<br> <br />4<br> ...<br> <br />6<br> ...<br> <br />8<br> ...<br> <br />10<br> ...<br> <br />Is it recommended to use CSS In JS technique in React?<br />React does not have any opinion about how styles are defined but if you are<br />a beginner then good starting point is to define your styles in a separate<br />*<br> ...<br> This functionality<br />is not part of React but came from third-party libraries<br> ...<br> <br />� Back to Top<br /><br />144<br /><br /> 302<br> ...<br> But you can try Hooks in a few components(or new components)<br />without rewriting any existing code<br> ...<br> <br />� Back to Top<br />303<br> ...<br> <br />Let’s take an example in which it fetches list of react articles from the API<br />import React, { useState, useEffect } from 'react';<br />import axios from 'axios';<br />function App() {<br />const [data, setData] = useState({ hits: [] });<br />useEffect(() => {<br />(async () => {<br />const result = await axios(<br />'http://hn<br> ...<br> com/api/v1/search?query=react',<br />);<br />setData(result<br> ...<br> hits<br> ...<br> objectID}><br /><a href={item<br> ...<br> title}</a><br /></li><br />))}<br /></ul><br />);<br />}<br />export default App;<br /><br />145<br /><br /> Remember we provided an empty array as second argument to the effect<br />hook to avoid activating it on component updates but only on mounting<br />of the component<br> ...<br> e, It fetches only on component mount<br> ...<br> <br />Is Hooks cover all use cases for classes?<br />Hooks doesn’t cover all use cases of classes but there is a plan to add<br />them soon<br> ...<br> <br />� Back to Top<br />305<br> ...<br> 8 release for<br />below packages<br />1<br> ...<br> <br />3<br> ...<br> <br /><br />React<br />React<br />React<br />React<br /><br />DOM<br />DOM Server<br />Test Renderer<br />Shallow Renderer<br /><br />� Back to Top<br />306<br> ...<br> The first item is the current value, and the second<br />is a function that updates the value<br> ...<br> This is why we use<br />array destructuring instead<br> ...<br> <br />What are the sources used for introducing hooks?<br />Hooks got the ideas from several different sources<br> ...<br> Previous experiments with functional APIs in the react-future repository<br />2<br> ...<br> State variables and state cells in DisplayScript<br> ...<br> Subscriptions in Rx<br> ...<br> Reducer components in ReasonReact<br> ...<br> <br />How do you access imperative API of web components?<br />Web Components often expose an imperative API to implement its functions<br> ...<br> But if you are<br />using third-party Web Components, the best solution is to write a React<br />component that behaves as a wrapper for your Web Component<br> ...<br> <br />What is formik?<br />Formik is a small react form library that helps you with the three major<br />problems,<br />1<br> ...<br> Validation and error messages<br />3<br> ...<br> <br />What are typical middleware choices for handling asynchronous<br />calls in Redux?<br />Some of the popular middleware choices for handling asynchronous calls<br />in Redux eco system are Redux Thunk, Redux Promise, Redux Saga<br> ...<br> <br />Do browsers understand JSX code?<br />No, browsers can’t understand JSX code<br> ...<br> The most<br />widely used transpiler right now is Babel<br> ...<br> <br />Describe about data flow in react?<br />React implements one-way reactive data flow using props which reduce<br />boilerplate and is easier to understand than traditional two-way data binding<br> ...<br> <br />What is react scripts?<br />The react-scripts package is a set of scripts from the create-react-app<br />starter pack which helps you kick off projects without configuring<br> ...<br> <br />� Back to Top<br />314<br> ...<br> <br />1<br> ...<br> <br />2<br> ...<br> CSS Reset/Normalize<br />4<br> ...<br> A fast interactive unit test runner with built-in support for coverage<br />reporting<br />6<br> ...<br> An offline-first service worker and a web app manifest, meeting all<br />the Progressive Web App criteria<br> ...<br> <br />What is the purpose of renderToNodeStream method?<br />The ReactDOMServer#renderToNodeStream method is used to generate<br />HTML on the server and send the markup down on the initial request for<br />faster page loads<br> ...<br> Note: Remember this method is not available in the<br />browser but only server<br> ...<br> <br />What is MobX?<br />MobX is a simple, scalable and battle tested state management solution<br />for applying functional reactive programming (TFRP)<br> ...<br> <br />What are the differences between Redux and MobX?<br />Below are the main differences between Redux and MobX,<br />Topic<br /><br />Redux<br /><br />MobX<br /><br />Definition<br /><br />It is a javascript library<br />for managing the<br />application state<br />It is mainly written in ES6<br /><br />It is a library for<br />reactively managing the<br />state of your applications<br />It is written in<br />JavaScript(ES5)<br />There is more than one<br />store for storage<br />Used for simple<br />applications<br />Provides better<br />performance<br />Uses observable to store<br />the data<br /><br />Programming<br />Data Store<br /><br />Performance<br /><br />There is only one large<br />store exist for data storage<br />Mainly used for large and<br />complex applications<br />Need to be improved<br /><br />How it stores<br /><br />Uses JS Object to store<br /><br />Usage<br /><br />� Back to Top<br />318<br> ...<br> But you may find<br />many resources or React ecosystem uses ES6 extensively<br> ...<br> Destructuring: To get props and use them in a component<br />“‘javascript // in es 5 var someData = this<br> ...<br> someData var<br />dispatch = this<br> ...<br> dispatch<br />// in es6 const { someData, dispatch } = this<br> ...<br> Spread operator: Helps in passing props down into a component<br />“‘javascript // in es 5<br />// in es6 <SomeComponent {…this<br> ...<br> Arrow functions: Makes compact syntax javascript<br />// es 5<br />var users = usersList<br> ...<br> name}</li><br />})<br />// es 6<br />const users<br />= usersList<br> ...<br> name}</li>);<br />� Back to Top<br />319<br> ...<br> It allows<br />React to interrupt a long-running render to handle a high-priority event<br> ...<br> e, When you enabled concurrent Mode, React will keep an eye on other<br />tasks that need to be done, and if there’s something with a higher priority<br />it will pause what it is currently rendering and let the other task finish<br />first<br> ...<br> Part of an app by wrapping with ConcurrentMode<br /><React<br> ...<br> unstable_ConcurrentMode><br />// 2<br> ...<br> unstable_createRoot(domNode)<br> ...<br> <br /><br />150<br /><br /> What is the difference between async mode and concurrent<br />mode?<br />Both refers the same thing<br> ...<br> The name has been changed to highlight<br />React’s ability to perform work on different priority levels<br> ...<br> <br />� Back to Top<br />321<br> ...<br> 9?<br />Yes, you can use javascript: URLs but it will log a warning in the console<br> ...<br> <br />const companyProfile = {<br />website: "javascript: alert('Your website is hacked')",<br />};<br />// It will log a warning<br /><a href={companyProfile<br> ...<br> <br />� Back to Top<br />322<br> ...<br> It assumes that<br />any function starting with ”use” and a capital letter right after it is a<br />Hook<br> ...<br> Calls to Hooks are either inside a PascalCase function (assumed to<br />be a component) or another useSomething function (assumed to be<br />a custom Hook)<br> ...<br> Hooks are called in the same order on every render<br> ...<br> <br />What is the difference between Imperative and Declarative in<br />React?<br />Imagine a simple UI component, such as a “Like” button<br> ...<br> <br />The imperative way of doing this would be:<br />151<br /><br /> if( user<br> ...<br> You can imagine how complex<br />this could be in a real-world scenario<br> ...<br> state<br> ...<br> <br />� Back to Top<br />324<br> ...<br> <br />2<br> ...<br> <br />4<br> ...<br> <br />How do you make sure that user remains authenticated on page<br />refresh while using Context API State Management?<br />When a user logs in and reload, to persist the state generally we add the<br />load user action in the useEffect hooks in the main App<br> ...<br> While using<br />Redux, loadUser action can be easily accessed<br> ...<br> js<br />import {loadUser} from '<br> ...<br> dispatch(loadUser());<br />• But while using Context API, to access context in App<br> ...<br> js so that App<br> ...<br> Now<br />whenever the page reloads, no matter what route you are on, the user will<br />be authenticated as loadUser action will be triggered on each re-render<br> ...<br> js<br />import<br />import<br />import<br />import<br /><br />React from 'react';<br />ReactDOM from 'react-dom';<br />App from '<br> ...<br> /context/auth/AuthState'<br /><br />ReactDOM<br> ...<br> StrictMode><br /><AuthState><br /><App /><br /></AuthState><br /></React<br> ...<br> getElementById('root')<br />);<br />App<br> ...<br> getItem('token');<br />if(!token){<br />dispatch({<br />type: ERROR<br />})<br />}<br />setAuthToken(token);<br />try {<br />const res = await axios('/api/auth');<br />153<br /><br /> dispatch({<br />type: USER_LOADED,<br />payload: res<br> ...<br> data<br />})<br />} catch (err) {<br />console<br> ...<br> <br />What are the benefits of new JSX transform?<br />There are three major benefits of new JSX transform,<br />1<br> ...<br> The compiled output might improve the bundle size in a small<br />amount<br />3<br> ...<br> <br />� Back to Top<br />327<br> ...<br> i<br> ...<br> <br />Let’s take an example to look at the main differences between the old and<br />the new transform,<br />Old Transform:<br />import React from 'react';<br />function App() {<br />return <h1>Good morning!!</h1>;<br />}<br />Now JSX transform convert the above code into regular JavaScript as<br />below,<br />import React from 'react';<br />function App() {<br /><br />154<br /><br /> return React<br> ...<br> <br />� Back to Top<br />328<br> ...<br> The generated project setup includes,<br />1<br> ...<br> <br />3<br> ...<br> <br /><br />Redux Toolkit and React-Redux dependencies<br />Create and configure Redux store<br />React-Redux <Provider> passing the store to React components<br />Small “counter” example to demo how to add redux logic and ReactRedux hooks API to interact with the store from components<br /><br />The below commands need to be executed along with template option as<br />below,<br />1<br> ...<br> Typescript template:<br />npx create-react-app my-app --template redux-typescript<br />� Back to Top<br />329<br> ...<br> These components allow us to load components from the backend<br> ...<br> <br />� Back to Top<br />330<br> ...<br> <br />� Back to Top<br />331<br> ...<br> This can happen when<br />you are trying to do some computations using a state variable and unknowingly save the result in the same state variable<br> ...<br> assign({}, …) or spread syntax<br> ...<br> <br />Ex: “‘javascript class A extends React<br> ...<br> state = { loading: false } }<br />componentDidMount() { let { loading } = this<br> ...<br> js, always<br />using setState to make updates, and returning new instances in reducers<br />when sending updated state values<br> ...<br> <br />156<br /><br /> What is the difference between useState and useRef hook?<br />1<br> ...<br> Essentially, useRef is like a “box” that can hold a<br />mutable value in its (<br> ...<br> <br />2<br> ...<br> While<br />useRef allows refrencing DOM elements<br> ...<br> We cannot guarantee that these questions will actually be asked during your interview process, nor should you focus<br />on memorizing all of them<hr /><div class="preview_top"><b>Title:</b> Reactjs Interview Questions<br/><b>Description:</b> React is a JavaScript-based UI development library. Facebook and an open-source developer community run it. Although React is a library rather than a language, it is widely used in web development. The library first appeared in May 2013 and is now one of the most commonly used frontend libraries for web development.in this notes i have done 300+ interview questions and answers so that is best for interview from my side<br/><div class="noteinfo"><a class="buybasket" href="/buy/273454">Buy These Notes</a><a class="action preview" href="preview/273454">Preview</a></div></div> </div> </div> </div> <div class="container"> <div id="footer"> <ul class="info"> <li><a href="become-a-notesale-ambassador">Become a Notesale Ambassador</a></li> </ul> <ul class="anc"> <li><a href="terms-and-conditions">Ts and Cs</a></li> <li class="last"><a href="contact-us">Contact Us</a></li> </ul> </div> </div> <script type="text/javascript" src="/path.js"></script> <script type="text/javascript" src="/notesale.js"></script> </body> </html>